/*
 * @Author: chengsl
 * @Date: 2022-11-03 18:38:37
 * @LastEditors: chengsl
 * @LastEditTime: 2022-12-01 16:43:58
 * @Description: file content
 */
var mysql = require('mysql')
var { Logger } = require('./log/logger')
const logger = new Logger({fileName:'dao.js'})
var { errorToString, getIWantObjectListByClass } = require('./utils')
var { User } = require('./DTO/user')
var connection = mysql.createConnection({
  host: '192.168.13.15',
  user: 'root',
  password: 'Mysql@2018',
  // database: 'aj_report',
  database: 'udaam-v3-demo',
})
connection.connect()
// .then(res => {
    // logger.info('数据库连接成功 ---老程')
// })

const daoObj = {
  select: function (params) {
    // logger.info(`DAO:${params}`)
    return new Promise((resolve, reject) => {
      try {
        //设计了几个参数制作sql语句
        let { tableName, pageNo, pageSize, orderBy, orderByKey, limit1, limit2 } = params
        var sql = `SELECT * FROM ${tableName ? tableName : 'tb_user'}${
          orderBy ? ` order by ${orderByKey || 'id'} ${orderBy}` : ''}${
            limit1 ? ` limit ${limit1}${limit2 ? `,${limit2}` : '' }` : ''
          }${
          pageNo && pageSize
            ? ` limit ${(pageNo - 1) * pageSize},${pageSize}`
            : ''
        }`
        if(!sql.includes('limit')) {
          sql = sql + ' limit 10'
        }
        logger.info(`sql语句:${sql}`)
        connection.query(sql, function (err, result) {
          if (err) {
            logger.info(`[SELECT ERROR] - ${err.message}`)
            reject('[SELECT ERROR] - ' + err.message)
          } else {
            // logger.info('--------------------------SELECT----------------------------')
            // logger.info(result)
            resolve(getIWantObjectListByClass(result, User))
            // logger.info(`------------------------------------------------------------\n\n`)
          }
        })
      } catch (error) {
        reject('SQL层逻辑出错:' + errorToString(error))
      }
      // connection.release()
      // connection.end();
    })
  },
  add: function (params) {
    return '暂未开发'
  },
  del: async function (params) {
    return '暂未开发'
  },
  upd: function (params) {
    return '暂未开发'
  },
}

module.exports = {
  daoObj,
}
